package com.yunjinsuke.recharge.controller;

import com.yunjinsuke.recharge.controller.api.APIEnum;
import com.yunjinsuke.recharge.controller.api.ApiResponse;
import com.yunjinsuke.recharge.entity.Merchant;
import com.yunjinsuke.recharge.redis.RedisKeyUtil;
import com.yunjinsuke.recharge.redis.RedisUtil;
import com.yunjinsuke.recharge.service.MerchantService;
import lombok.Data;
import org.springframework.web.bind.annotation.*;


/**
 * 商户
 */
@RestController
@RequestMapping("merchant")
public class MerchantController {


    private final RedisUtil redisUtil;

    private final MerchantService merchantService;

    public MerchantController(MerchantService merchantService, RedisUtil redisUtil) {
        this.merchantService = merchantService;
        this.redisUtil = redisUtil;
    }

    /**
     * 商户信息
     *
     * @param appId 应用ID
     * @return 商户信息
     */
    @GetMapping("info")
    public ApiResponse merchantInfo(@RequestParam("appId") String appId) {
        // TODO 登录或其他鉴权方式才能获取
        if (redisUtil.hasKey(RedisKeyUtil.appKey(appId))) {
            Merchant merchant = (Merchant) redisUtil.get(RedisKeyUtil.appKey(appId));
            return new ApiResponse(new VoMerchant(merchant));
        } else {
            return new ApiResponse(APIEnum.INVALID_REQUEST, "appId 无效");
        }
    }

    /**
     * 开通商户
     *
     * @return 商户信息
     */
    // TODO 加权
    @PostMapping("applyFor")
    public ApiResponse merchantInfo() {
        // TODO 运营人员分配
        Merchant merchant = merchantService.createMerchant();
        return new ApiResponse(new VoMerchant(merchant));
    }

    @Data
    public static class VoMerchant {
        public VoMerchant(Merchant merchant) {
            this(merchant.getAppId(), merchant.getId(), merchant.getMchKey());
        }

        public VoMerchant(String appId, String mchId, String mchKey) {
            this.appId = appId;
            this.mchId = mchId;
            this.mchKey = mchKey;
        }

        /**
         * appID
         */
        private String appId;

        /**
         * 商户号
         */
        private String mchId;

        /**
         * 商户密钥
         */
        private String mchKey;

    }

}
